<template>
    <div>
        <!-- 查询区域 -->
        <div class="card query-card">
            <el-input
                    v-model="data.title"
                    placeholder="请输入账号"
                    :prefix-icon="Search"
                    class="input-field"
            />
            <el-input
                    v-model="data.content"
                    placeholder="请输入昵称"
                    :prefix-icon="Search"
                    class="input-field"
            />
            <el-button type="primary" @click="load">查 询</el-button>
        </div>
        <!-- 操作按钮区域 -->
        <div class="card action-card">
            <el-button type="danger" @click="deleteSelectedNotices">批量删除</el-button>
            <el-button type="primary" @click="toAddPage">新 增</el-button>
        </div>
        <!-- 表格区域 -->
        <div class="card table-card">
            <el-table
                    v-loading="loading"
                    table-layout="auto"
                    :data="data.userFormList"
                    style="width: 100%"
                    :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="title" label="公告标题"/>
                <el-table-column prop="content" label="公告内容"/>
                <el-table-column prop="creatorId" label="发布人"/>
                <el-table-column prop="publishTime" label="发布时间">
                    <template #default="scope">
                        {{ formattedPublishTime(scope.row.publishTime) || '--------' }}
                    </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="修改时间">
                    <template #default="scope">
                        {{ formattedPublishTime(scope.row.updateTime) || '--------' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button type="primary" icon="Edit" circle @click="toEditPage(scope.row)"></el-button>
                        <el-button type="danger" icon="Delete" circle @click="deleteNotice(scope.row.id)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页区域 -->
        <div class="card pagination-card">
            <el-pagination
                    v-model:current-page="data.currentPage"
                    v-model:page-size="data.pageSize"
                    :page-sizes="[5, 10, 20, 30]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="data.total"
                    @size-change="load"
                    @current-change="load"
            />
        </div>
        <!-- 新增/编辑用户抽屉 -->
        <el-drawer
                title="公告信息"
                v-model="drawerVisible"
                size="30%"
        >
            <div class="demo-drawer__content">
                <el-form
                        :model="data.form"
                        :rules="rules"
                        label-width="auto"
                        status-icon
                        ref="formRef"
                        class="form-container"
                >
                    <el-form-item label="公告标题" prop="title">
                        <el-input v-model="data.form.title"/>
                    </el-form-item>
                    <el-form-item label="公告内容" prop="content">
                        <el-input type="textarea" :rows="3" v-model="data.form.content"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">提交</el-button>
                        <el-button @click="cancelDrawer">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import myAxios from "@/axios/axios.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {formattedPublishTime} from "@/tools/date.js";

// 加载状态
const loading = ref(true);
// 抽屉可见状态
const drawerVisible = ref(false);
const formRef = ref();
const dialogFormVisible = ref(false);
// 路由实例
const router = useRouter();

// 获取本地存储的用户信息
const user = JSON.parse(localStorage.getItem("code_user"));

// 表格数据及分页信息
const data = reactive({
    title: "",
    content: "",
    publishTime: '',
    createTime: '',
    updateTime: '',
    pageNum: 1,
    pageSize: 10,
    currentPage: 1,
    total: 100,
    userFormList: [],
    form: {},
    selectedUsers: [],
});

// 表单验证规则
const rules = reactive({
    title: [
        {required: true, message: '请输入公告标题', trigger: 'blur'}
    ],
    content: [
        {required: true, message: '请输入公告内容', trigger: 'blur'}
    ]
});

// 加载表格数据
const load = async () => {
    try {
        const res = await myAxios.get("/notice/list/page", {
            params: {
                title: data.title,
                content: data.content,
                pageNum: data.pageNum,
                pageSize: data.pageSize,
            },
        });
        if (res.code === 0 && res.data) {
            data.userFormList = res.data.records;
            data.total = res.data.total;
        } else {
            ElMessage.error("数据加载失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("数据加载出错:", error);
    } finally {
        loading.value = false;
    }
};

// 处理表格选择变化
const handleSelectionChange = (val) => {
    data.selectedUsers = val;
    console.log(val);
};

// 打开新增公告抽屉
const toAddPage = () => {
    data.form = {};
    drawerVisible.value = true;
};

// 打开编辑公告抽屉
const toEditPage = (row) => {
    data.form = JSON.parse(JSON.stringify(row));
    drawerVisible.value = true;
};

// 提交表单
const onSubmit = () => {
    formRef.value.validate((valid) => {
        if (!valid) {
            return;
        }
        if (data.form.id) {
            updateNotice();
        } else {
            addNotice();
        }
    });
};

// 新增公告
const addNotice = async () => {
    try {
        const res = await myAxios.post("/notice/add", data.form);
        if (res.code === 0) {
            ElMessage.success("公告创建成功");
            drawerVisible.value = false;
            await load();
        } else {
            ElMessage.error("公告创建失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("公告创建出错:", error);
    }
};

// 更新公告
const updateNotice = async () => {
    try {
        const res = await myAxios.post("/notice/update", data.form);
        if (res.code === 0) {
            ElMessage.success("公告更新成功");
            drawerVisible.value = false;
            await load();
        } else {
            ElMessage.error("公告更新失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("公告更新出错:", error);
    }
};

// 删除公告
const deleteNotice = async (id) => {
    try {
        await ElMessageBox.confirm(
            '此操作将永久删除该公告, 是否继续?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        const res = await myAxios.delete(`/notice/delete/${id}`);
        if (res.code === 0) {
            ElMessage.success("公告删除成功");
            await load();
        } else {
            ElMessage.error("公告删除失败");
        }
    } catch (error) {
        // 判断是否是用户取消操作
        if (error === 'cancel') {
            // 用户点击了“取消”，不显示错误提示
            return;
        }

        ElMessage.error("网络请求出错，请稍后重试");
        console.error("公告删除出错:", error);
    }
};

// 批量删除公告
const deleteSelectedNotices = async () => {
    if (data.selectedUsers.length === 0) {
        ElMessage.warning("请选择要删除的公告");
        return;
    }
    try {
        const ids = data.selectedUsers.map(user => user.id);
        const res = await myAxios.post("/notice/batchDelete", { ids });
        if (res.code === 0) {
            ElMessage.success("公告批量删除成功");
            await load();
        } else {
            ElMessage.error("公告批量删除失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("公告批量删除出错:", error);
    }
};

// 关闭新增/编辑抽屉
const cancelDrawer = () => {
    drawerVisible.value = false;
};

// 组件挂载时加载数据
onMounted(() => {
    load();
});
</script>

<style scoped>
.card {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 5px;
}

.query-card {
    display: flex;
    align-items: center;
}

.input-field {
    width: 240px;
    margin-right: 10px;
}

.action-card {
    display: flex;
    align-items: center;
}


.demo-drawer__content {
    padding: 20px;
}

.form-container {
    max-width: 400px;
}


:deep(.el-table__header th) {
    text-align: center;
}
</style>
